﻿using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Linq;
using exam.Document;

string docFilePath = "cards.docx";
string questionsFilePath = "questions.txt";
string numbersFilePath = "numbers.txt";

if (File.Exists(docFilePath))
{
    File.Delete(docFilePath);
}

if (!File.Exists(questionsFilePath))
{
    throw new Exception($"Not found '{questionsFilePath}' file");
}

if (!File.Exists(numbersFilePath))
{
    throw new Exception($"Not found '{numbersFilePath}' file");
}

string[] questions = File.ReadAllLines(questionsFilePath);
string[] questionsNumbers = File.ReadAllLines(numbersFilePath);

var numbers = questionsNumbers.Select(item => item.Split("\t").Select(x => int.Parse(x)).ToArray()).ToArray();

using WordprocessingDocument wordDocument = WordprocessingDocument.Create(docFilePath, WordprocessingDocumentType.Document);

// Add a main document part. 
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

// Create the document structure and add some text.
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());

int cardCount = numbers[0].Count();

for (int i = 0; i < cardCount; i++)
{
    int number = i + 1;
    if (number % 3 == 2)
    {
        body.AppendChild(Structure.GetEmptyParagraph());
    }

    var card = BuildCard(questions, numbers, number);
    card.AddCardToBody(body);

    if (number % 3 == 0 && i != cardCount - 1)
    {
        body.AppendChild(
            new Paragraph(
                new Run(
                    new Break() { Type = BreakValues.Page })));
    }
    if (number % 3 == 2)
    {
        body.AppendChild(Structure.GetEmptyParagraph());
    }
}

mainPart.Document.Save();

static Card BuildCard(string[] questions, int[][] numbers, int number)
{
    var card = new Card() { Number = number };

    var cardQuestions = new List<string>();
    for (int j = 0; j < numbers.Count(); j++)
    {
        int questionNumber = numbers[j][number - 1] - 1;
        string s = questions[questionNumber];
        cardQuestions.Add($"Вопрос {j + 1}. {s}");
    }

    card.Questions = cardQuestions.ToArray();
    return card;
}